import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { BladeContainerBase } from "../../../../../shared/blade/blade-container-base";
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";
import { BladeData } from "../../../../../shared/blade/blade-data";
import { Blade } from "../../../../../shared/blade/blade.model";
import { Command } from "../../../../../shared/toolbar.service";
import { Fault } from "../../../../../entity/fault.model";
import { FaultService } from "../../../../../service/fault.service";
import { AlarmCategory } from "../../../../../entity/alarm-category.model";
import { FaultLevel } from "../../../../../entity/fault-level.model";
import { TurbComponent } from "../../../../../entity/turbcomponent.model";
@Component({
  selector: 'app-fault-alarm-edit',
  templateUrl: './fault-alarm-edit.component.html',
  styleUrls: ['./fault-alarm-edit.component.css']
})
export class FaultAlarmEditComponent extends BladeContainerBase<Fault> {
  @Output() clearText = new EventEmitter<boolean>();
  /**
   * 当前测点名称
   * 
   * @type {string}
   * @memberof FaultAlarmEditComponent
   */
  brand: string;

  /**
  * 设备集合
  * 
  * @type {string[]}
  * @memberof FaultAlarmEditComponent
  */
  turbComponenData: TurbComponent[] = [];
  turbComponentList: TurbComponent[] = [];

  /**
   * 子系统集合
   * 
   * @type {string[]}
   * @memberof FaultAlarmEditComponent
   */
  subComponents: TurbComponent[] = [];
  isShowSub: boolean;

  /**
   * 部件集合
   * 
   * @type {string[]}
   * @memberof FaultAlarmEditComponent
   */
  partsData: PartsData[] = [];
  parts: TurbComponent[] = [];
  isShowPart: boolean;

  /**
   * 测点名称集合
   * 
   * @type {string[]}
   * @memberof FaultAlarmEditComponent
   */
  tagData: string[];
  constructor(
    private fb: FormBuilder,
    private faultService: FaultService,
  ) {
    super(fb)
  }

  ngOnInit() {
    this.turbComponenData = [...this.parentEntity.turbComponentList];
    this.turbComponentList = [...this.parentEntity.turbComponentList].filter(o => o.parentId == 0 || o.parentId == null);
    if (!this.isNew) {

      this.commands = [
        new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
      this.isEdit();
    };
    if (this.parentEntity.current.multipleValue) {
      this.tagData = this.parentEntity.tags.map(o => o.tagName);

      if (this.currentEntity.tagId) {
        let i = this.parentEntity.tags.findIndex(o => o.tagId == this.currentEntity.tagId);
        if (i > -1)
          this.brand = this.parentEntity.tags[i].tagName;
      }
    }
    super.ngOnInit();
  }

  isEdit() {
    this.subComponents = [];
    this.partsData = [];
    this.parts = [];

    //当前系统下的子系统；
    this.subComponents = this.turbComponenData.filter(o => o.parentId == this.currentEntity.turbComponentId);
    //当前实体下选中的子系统或零部件
    let subComponentIds = this.currentEntity.subComponentIds != null ? this.currentEntity.subComponentIds.split('|') : [];
    let partsIds = this.currentEntity.partsIds != null ? this.currentEntity.partsIds.split('|') : [];


    if (subComponentIds.length > 0) {
      this.subComponents.forEach(component => {
        subComponentIds.forEach(id => {
          if (component.turbComponentId == parseInt(id)) {
            component.isChecked = true;
            if (component.isChecked) {

              //过滤子系统下选中的零部件；
              this.parts.push(...this.turbComponenData.filter(k => k.parentId == component.turbComponentId));
              this.partsData.push({
                parts: [...this.turbComponenData.filter(k => k.parentId == component.turbComponentId)],
                subComponent: this.subComponents.find(k => k.turbComponentId == component.turbComponentId)
              })

              //如果当前报警下配置了零部件，给当前打勾；
              if (partsIds.length > 0) {
                this.parts.forEach(part => {
                  partsIds.forEach(id => {
                    if (part.turbComponentId == parseInt(id)) {
                      part.isChecked = true;
                    }
                  })
                })
              }

            }
          }
        })
        this.isShowPart = (this.partsData.map(o => o.parts)).length > 0 ? true : false;
      })
    }

  }

  initData(): any | Observable<any> | Promise<any> {
    this.formPatchValue(this.currentEntity);
  }
  exeSaveChange(blade: any): void {
    this.saveChange();
  }
  canSaveChange(blade: any): boolean {
    if (this.parentEntity.current.multipleValue) {
      return (this.hasChange() || ((this.parentEntity.tags.findIndex(o => o && (o.tagName == this.brand)) > -1) || this.brand == "") && this.brand != this.currentEntity.tagName) && !this.hasError();
    }

    return this.hasChange() && !this.hasError();
  }
  exeReset(blade: any): void {
    this.brand = this.currentEntity.tagName;
    return this.formGroup.reset(this.currentEntity);
  }
  canReset(blade: any): boolean {
    if (this.parentEntity.current.multipleValue) {
      return (this.hasChange() || ((this.parentEntity.tags.findIndex(o => o && (o.tagName == this.brand)) > -1) || this.brand == "") && this.brand != this.currentEntity.tagName) && !this.hasError();
    }
    return this.hasChange();
  }
  createForm() {
    let obj: {} = {
      "faultCode": [this.currentEntity.faultCode,
      [
        Validators.required,
        Validators.pattern("^[0-9]+$"),
        Validators.maxLength(20),
      ], (control: FormControl): any => this.faultCodeAsnyValidator(control)
      ],
      "faultDesc": [this.currentEntity.faultDesc,
      [
        Validators.required,
        Validators.maxLength(100),
      ], (control: FormControl): any => this.faultDescAsnyValidator(control)],
      "turbComponentId": [this.currentEntity.turbComponentId],
      "subComponentIds": [this.currentEntity.subComponentIds],
      "partsIds": [this.currentEntity.partsIds],
      "alarmCategoryId": [this.currentEntity.alarmCategoryId],
      "faultLevelId": [this.currentEntity.faultLevelId],
      "unAlarm": [this.currentEntity.unAlarm],

    };
    this.formGroup = this.fromBuider.group(obj);

  }

  faultCodeAsnyValidator(control: FormControl) {
    if (!control.value || control.value == this.currentEntity.faultCode) {
      return Observable.of(null);
    }
    return this.faultService.faultCodeService(control.value, this.currentEntity.schemeId, this.currentEntity.faultId)
      .map(res => res ? { exist: true } : null);
  }

  faultDescAsnyValidator(control: FormControl) {
    if (!control.value || control.value == this.currentEntity.faultDesc) {
      return Observable.of(null);
    }
    return this.faultService.faultDescService(control.value, this.currentEntity.schemeId, this.currentEntity.faultId)
      .map(res => res ? { exist: true } : null);
  }


  /**
  * 设置表单错误对象
  * 
  * 
  * @memberof BladeContainerBase
  */
  setFormError(): void {
    this.formErrors = {
      "faultCode": "",
      "faultDesc": ""
    };
  }
  /**
  * 设置表单验证信息
  * 
  * 
  * @memberof BladeContainerBase
  */
  setValidationMessages(): void {
    this.validationMessages = {

      "faultCode": {
        'required': '故障码不能为空。',
        'pattern': '故障码必须由数字组成。',
        'maxlength': '故障码不能多于20个字符长度。',
        "exist": "故障码已存在"
      },
      "faultDesc": {
        'required': '故障描述不能为空。',
        'maxlength': '故障描述不能多于100个字符长度。',
        "exist": "故障信息已存在"
      },
    };
  }

  onComponentChange(ev) {
    if (parseInt(ev) == this.currentEntity.turbComponentId) {
      this.isEdit();
    } else {
      this.subComponents = [];
      this.partsData = [];
      this.parts = [];
      this.subComponents = this.turbComponenData.filter(o => o.parentId === parseInt(ev));
      if (this.subComponents.length < 1) {
        this.isShowPart = false;
      } else {
        this.isShowPart = true;
      }
    }

  }

  subComponentChecked(check: boolean, value: TurbComponent) {
    value.isChecked = check;
    let filter = this.subComponents.filter(o => o.isChecked);
    if (filter) {
      //选中的子系统ids
      let subComponentIds = filter.map(o => o.turbComponentId);
      this.getPartsData(subComponentIds);
      //设置实体的子系统表单值
      this.formGroup.controls["subComponentIds"].setValue(subComponentIds.join("|"));
    }
    else {
      this.formGroup.controls["subComponentIds"].setValue("");
    }

  }

  getPartsData(subComponentIds: number[]) {
    this.partsData = [];
    this.parts = [];
    //根据子系统过滤系统下的部件
    subComponentIds.forEach(o => {
      this.parts.push(...this.turbComponenData.filter(k => k.parentId == o));
      this.partsData.push({
        parts: [...this.turbComponenData.filter(k => k.parentId == o)],
        subComponent: this.subComponents.find(k => k.turbComponentId == o)
      })
    })
  }

  partChecked(check: boolean, value: TurbComponent) {
    value.isChecked = check;
    this.filterPart();
  }

  filterPart() {

    let filter = this.parts.filter(o => o.isChecked);
    if (filter) {
      let partsIds = filter.map(o => o.turbComponentId);
      this.formGroup.controls["partsIds"].setValue(partsIds.join("|"));
    }
    else {
      this.formGroup.controls["partsIds"].setValue("");
    }
  }

  beforSave() {
    //保存之前判断子系统是否选中，如果未选中，当前下部件选中清空；
    let unfilter = this.subComponents.filter(o => !o.isChecked);
    if (unfilter) {
      let currtPart: TurbComponent[] = [];
      let subComponentIds = unfilter.map(o => o.turbComponentId);
      subComponentIds.forEach(o => {
        currtPart.push(...this.turbComponenData.filter(k => k.parentId == o));
        currtPart.forEach(o => {
          if (o.isChecked) {
            o.isChecked = false;
          }
        })
      })
    }

    this.filterPart();
  }

  /**
   * 创建一个测点信息
   * 
   * 
   * @memberof TurbstatusEditComponent
   */
  onCreate() {
    if (!this.hasError()) {
      this.changeCurrent();
      this.faultService.create(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(this.parentEntity.current);
            this.bladeService.closeBlade(this.currentBlade);
          } else {
            throw new Error("数据新增失败！");
          }
        })
        .catch(err => {
          console.log(err)
        })
        .then(res => this.bladeData.isLoading = false);

    }
  }
  /**
   * 
   * 
   * 
   * @memberof TagsEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {

    if (this.canSaveChange(this.currentBlade)) {
      this.beforSave()
      this.changeCurrent()
      return this.faultService.update(this.currentEntity)
        .then(res => {
          if (res) {
            this.clearText.emit(true);
            (this.parentBlade.bladeContainerInstance).refresh(this.parentEntity.current);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
          throw new Error("数据更新失败！")

        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }
  changeCurrent() {
    this.bladeData.isLoading = true;
    let formValue = this.formGroup.value;
    this.currentEntity.faultCode = formValue.faultCode;
    this.currentEntity.faultDesc = formValue.faultDesc;
    this.currentEntity.alarmCategoryId = formValue.alarmCategoryId;
    this.currentEntity.turbComponentId = formValue.turbComponentId;
    this.currentEntity.subComponentIds = formValue.subComponentIds;
    this.currentEntity.partsIds = formValue.partsIds;
    this.currentEntity.faultLevelId = formValue.faultLevelId;
    this.currentEntity.unAlarm = formValue.unAlarm;
    if (this.parentEntity.current.multipleValue) {
      let index = this.parentEntity.tags.findIndex(o => o.tagName == this.brand);
      if (index <= -1) return false;
      this.currentEntity.tagId = this.parentEntity.tags[index].tagId;
    }
  }
  filterBrands(event) {
    let tagData: string[] = [];
    for (let i = 0; i < this.parentEntity.tags.length; i++) {
      let brand: string = this.parentEntity.tags[i].tagName;
      if (brand.toLowerCase().indexOf(event.query.toLowerCase()) == 0) {
        tagData.push(brand);
      }
    }
    this.tagData = tagData;
  }

  handleDropdownClick(event) {
    setTimeout(() => {
      this.tagData = this.parentEntity.tags.map(o => o.tagName);
    }, 100)
  }
}

interface PartsData {
  parts: TurbComponent[],
  subComponent: TurbComponent
}



// WEBPACK FOOTER //
// ./src/app/module/basic/model/fault-alarm/fault-alarm-edit/fault-alarm-edit.component.ts